package com.wty.cmims.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wty.cmims.mapper.HealthRecordMapper;
import com.wty.cmims.mapper.MedicalHistoryMapper;
import com.wty.cmims.mapper.ResidentMapper;
import com.wty.cmims.pojo.Code;
import com.wty.cmims.pojo.HealthRecord;
import com.wty.cmims.pojo.MedicalHistory;
import com.wty.cmims.pojo.Resident;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.pojo.User;
import com.wty.cmims.service.UserService;
import com.wty.cmims.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
* @author wty
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-10-01 18:06:53
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResidentMapper residentMapper;
    @Autowired
    private HealthRecordMapper healthRecordMapper;
    @Autowired
    private MedicalHistoryMapper medicalHistoryMapper;

    /**
     * 用户注册
     *
     * @param name
     * @param account
     * @param password
     * @param role
     * @return
     */
    @Transactional
    @Override
    public ResponseResult<Map<String, Object>> userRegister(String name, String account, String phone, String password, Integer role) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        // 判断账号是否已存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account).eq(User::getIsDel, 0);
        User same = this.getOne(wrapper);
        if (same != null){
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("账号" + account + "已注册");
            return responseResult;
        }
        // 判断手机号是否已注册
        LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(User::getPhone, phone).eq(User::getIsDel, 0);
        User same2 = this.getOne(wrapper2);
        if (same2 != null){
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("手机号" + phone + "已注册");
            return responseResult;
        }
        // 创建User对象赋值并插入数据表
        User user = new User();
        user.setName(name);
        user.setAccount(account);
        user.setPhone(phone);
        // 密码进行MD5加密并加盐
        user.setPassword(SecureUtil.md5(password + account));
        user.setRole(role);
        boolean save = this.save(user);
        if (save){
            Resident resident = new Resident();
            resident.setUserId(user.getUserId());
            // 在resident表中插入一条只有user_id的数据
            int rowsResident = residentMapper.insert(resident);
            // 在healthrecord表中插入一条只有id和resident_id的数据
            HealthRecord healthRecord = new HealthRecord();
            healthRecord.setResidentId(resident.getUserId());
            int rowsHealthrecord = healthRecordMapper.insert(healthRecord);
            // 居民相关信息全部注册成功，获取居民基本信息
            if (rowsResident > 0 && rowsHealthrecord > 0) {
                Map<String,Object> paramsMap = new HashMap<>();
                paramsMap.put("account",account);
                Map<String, Object> map = residentMapper.findResidentInfo(paramsMap);
                responseResult.setData(map);
                responseResult.setCode(Code.SUCCESS);
                responseResult.setMessage("注册成功");
            } else {
                responseResult.setCode(Code.ERROR);
                responseResult.setMessage("居民相关信息注册失败");
            }
        } else{
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("注册失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String, Object>> userLogin(String account, String password) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        // 对密码进行MD5加密并加盐
        password = SecureUtil.md5(password + account);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account).eq(User::getPassword, password).eq(User::getRole, 0).eq(User::getIsDel, 0);
        // 查询user
        User user = this.getOne(wrapper);
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("account",account);
        Map<String, Object> map = residentMapper.findResidentInfo(paramsMap);
        if (user != null){
            responseResult.setData(map);
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("登录成功");
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("账号或密码错误");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<User> userUpdate(User user) {
        ResponseResult<User> responseResult = new ResponseResult<>();
        boolean update = this.updateById(user);
        if (update){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("用户信息更新成功");
            responseResult.setData(user);
        } else{
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("用户信息更新失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Void> updatePassword(String account, String oldPassword, String newPassword) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account).eq(User::getPassword, SecureUtil.md5(oldPassword + account));
        User user = this.getOne(wrapper);
        if (user == null){
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("旧密码输入错误");
            return responseResult;
        }
        user.setPassword(SecureUtil.md5(newPassword + account));
        boolean update = this.updateById(user);
        if(update){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("密码修改成功");
        } else{
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("密码修改失败");
        }
        return responseResult;
    }
}